package updownLoad.download;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;

import sun.misc.BASE64Encoder;

public class DownLoadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String fileName = req.getParameter("downfile");
        fileName = new String(fileName.getBytes("iso-8859-1"), "utf-8"); //表单的编码永远是iso-8859-1,无法人为改变
        
        String root = this.getServletContext().getRealPath("/WEB-INF/Sources/");
        String filePath = root + "\\" + fileName;
        
        String encodefileName = filenameEncoding(fileName, req);        //须转成url编码, 不然中文文件名无法显示
        String contentDisposition = "attachment;filename=" + encodefileName; //浏览器解析响应头是解析url编码的, 所以须手动转
        String contentType = this.getServletContext().getMimeType(fileName);
        resp.setHeader("Content-Type", contentType);
        resp.setHeader("Content-Disposition", contentDisposition);
        
        InputStream fileIn = new FileInputStream(filePath);
        IOUtils.copy(fileIn, resp.getOutputStream());
        fileIn.close();
        
    }

    // 用来对下载的文件名称进行编码的！
    public static String filenameEncoding(String filename, HttpServletRequest request) throws IOException {
        String agent = request.getHeader("User-Agent"); // 获取浏览器
        if (agent.contains("Firefox")) {
            BASE64Encoder base64Encoder = new BASE64Encoder();
            filename = "=?utf-8?B?" + base64Encoder.encode(filename.getBytes("utf-8")) + "?=";
        } else if (agent.contains("MSIE")) {
            filename = URLEncoder.encode(filename, "utf-8");
        } else {
            filename = URLEncoder.encode(filename, "utf-8");
        }
        return filename;
    }

}
